#include "lyricslist.h"

LyricsList::LyricsList()
{

}

LyricsList::LyricsList(QString filePath)
{
    lyrics = new QMap<int,QString>;
    timeMap = new QMap<int,int>;
    if(filePath == "")
    {
        lyrics->insert(0,"暂无歌词");
    }
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        // 文件打开失败处理
        title = "暂未播放音乐";
        artist = "";
        album = "";
        lyrics->insert(0,"这首歌，暂无歌词～");
        return;
    }

    // 对每一行进行解析处理
    QTextStream in(&file);
    int i=0;
    while (!in.atEnd())
    {
        //获取没一行歌词
        QString line = in.readLine();

        // 提取时间标签
        int time = line.mid(1, 2).toInt()*60+line.mid(4,2).toInt();
        if(line.mid(1,2) == QString("ti"))
        {
            title = line.mid(line.indexOf(':') + 1,line.indexOf("]")-(line.indexOf(":")+1));
        }
        else if(line.mid(1,2) == QString("ar"))
        {
            artist = line.mid(line.indexOf(':') + 1,line.indexOf("]")-(line.indexOf(":")+1));
        }
        else if(line.mid(1,2) == QString("al"))
        {
            album = line.mid(line.indexOf(':') + 1,line.indexOf("]")-(line.indexOf(":")+1));
        }
        else
        {
            // 提取歌词内容
            QString text = line.mid(line.indexOf(']') + 1);
            lyrics->insert(time,text);
            timeMap->insert(i++,time);
        }
    }
}

void LyricsList::setMusicPath(QString filePath)
{
    lyrics->clear();
    timeMap->clear();
    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        // 文件打开失败处理
        title = "";
        artist = "";
        album = "";
        lyrics->insert(0,"暂无歌词");
        return;
    }

    // 对每一行进行解析处理
    int i = 0;
    QTextStream in(&file);
    while (!in.atEnd())
    {
        //获取没一行歌词
        QString line = in.readLine();

        // 提取时间标签
        int time = line.mid(1, 2).toInt()*60+line.mid(4,2).toInt();

//        qDebug()<<line.mid(1,2)<<endl;
        if(line.mid(1,2) == QString("ti"))
        {
            title = line.mid(line.indexOf(':') + 1,line.indexOf("]")-(line.indexOf(":")+1));
        }
        else if(line.mid(1,2) == QString("ar"))
        {
            artist = line.mid(line.indexOf(':') + 1,line.indexOf("]")-(line.indexOf(":")+1));
        }
        else if(line.mid(1,2) == QString("al"))
        {
            album = line.mid(line.indexOf(':') + 1,line.indexOf("]")-(line.indexOf(":")+1));
        }
        else
        {
            // 提取歌词内容
            QString text = line.mid(line.indexOf(']') + 1);
            if(text != "")
            {
                lyrics->insert(time,text);
                timeMap->insert(i++,time);
            }
        }
    }
}

QMap<int, int> &LyricsList::getCurrentLyricMapIndex()
{
    return *timeMap;
}

LyricsList::~LyricsList()
{
    //删除歌词map
    delete lyrics;
    //删除歌词、时间map
    delete timeMap;
}
